using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Xml;
using System.Xml.Xsl;
using APJ.Util;

namespace MTRC.ODMS.Web.SOM.CodeSetup
{
    /// <summary>
    /// author:Weiyudong modify by zengshunbo 2008-12-11 actionlog(0709)
    /// </summary>
    public partial class ContractorCompanyUpload : BasePage_SOM
    {
        #region MenuID

        protected override string MenuID
        {
            get
            {
                return "M140816";//set the Menu
            }
        }

        #endregion
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                SetLanguage();
            }
        }

        protected override void OnInit(EventArgs e)
        {
            this.ChangeLanguage += new MTRC.ODMS.Web.BasePage.ChangeLanguageEventHandler(this.ChangeLanguage_Click);
        }

        private void ChangeLanguage_Click(object sender, System.EventArgs e)
        {
            SetLanguage();
        }

        private void SetLanguage()
        {
            this.lblTitle.Text = this.GetLabel("SOM_CQAContractorCompanyUpload");
            this.lblFileToBeUploaded.Text = this.GetLabel("SOM_FileToBeUploaded", true);
            this.btnUpload.Text = this.GetLabel("SOM_Upload");
            this.btnDownTemplte.Text = this.GetLabel("SOM_DownloadEmptyTemplate");
            this.lblUploadNote.Text = this.GetLabel("SOM_Note");
            this.lblDownload.Text = this.GetLabel("SOM_DownloadTheCQAContractorCompany", true);
            this.btnDownMTR.Text = this.GetLabel("SOM_DownloadDown");
        }

        protected void btnUpload_Click(object sender, EventArgs e)
        {
            string fileName = "CQAContractorCompanyUpload_ERRORHighlight.xls";
            bool hasERROR = false;
            //check the file if null 
            if (this.txtfileUpload.PostedFile.ContentLength <= 0)
            {
                this.Alert(this.GetMessage("SOM_FilePathNull"));
                return;
            }

            //Add by LiangZehong on 2008-12-18, for issue 0634 Begin...
            string fileType = string.Empty;
            fileType = this.txtfileUpload.PostedFile.FileName.Substring(this.txtfileUpload.PostedFile.FileName.LastIndexOf(".") + 1);
            if (fileType.ToLower() != ("xls").ToLower())
            {
                this.Alert(this.GetMessage("SOM_FileTypeError"));
                return;
            }
            //End...

            XmlDocument xdoc = new XmlDocument();
            try
            {
                //load file
                xdoc.Load(this.txtfileUpload.PostedFile.InputStream);
                if (xdoc.GetElementsByTagName("Worksheet").Count > 1)
                {
                    Alert(GetMessage("SOM_OneSheetOnly"));
                    return;
                }
                //xdoc.Save(@"C:\hrm.xml");			//for debug
                string xpath = "ss:Workbook/ss:Worksheet/ss:Table/ss:Row[not (@ss:Hidden)]";
                System.Xml.XmlNamespaceManager xnm = new XmlNamespaceManager(xdoc.NameTable);

                xnm.AddNamespace("ss", "urn:schemas-microsoft-com:office:spreadsheet");

                XmlNodeList nodelist = xdoc.SelectNodes(xpath, xnm);
                int i = 0;
                XmlDocument xml = new XmlDocument();
                xml.LoadXml("<root/>");
                foreach (XmlNode node in nodelist)
                {
                    if (i > 0)		//0,  first row is head
                    {
                        //string QualCode = "", QualDesc = "", FlagSOMAR = "", FlagObsolete = "";
                        string companyCode = "";
                        string desc1 = "";
                        string desc2 = "";
                        string desc3 = "";
                        string address = "";
                        string location = "";                        
                        string flagObsolete = "";
                        
                        try
                        {
                            for (int j = 0, k = 0; j < node.ChildNodes.Count; j++)
                            {
                                if (node.ChildNodes[j].Attributes["ss:Index"] != null)//?
                                {
                                    int h = 0;
                                    if (int.TryParse(node.ChildNodes[j].Attributes["ss:Index"].Value, out h))
                                    {
                                        k = h - 1;
                                    }
                                }
                                switch (k)
                                {
                                    case 0:
                                        if (node.ChildNodes[j] != null && node.ChildNodes[j].ChildNodes[0] != null)
                                        {
                                            companyCode = node.ChildNodes[j].ChildNodes[0].InnerText.Trim();
                                        }
                                        break;
                                    case 1:
                                        if (node.ChildNodes[j] != null && node.ChildNodes[j].ChildNodes[0] != null)
                                        {
                                            desc1 = node.ChildNodes[j].ChildNodes[0].InnerText.Trim();
                                        }
                                        break;
                                    case 2:
                                        if (node.ChildNodes[j] != null && node.ChildNodes[j].ChildNodes[0] != null)
                                        {
                                            desc2 = node.ChildNodes[j].ChildNodes[0].InnerText.Trim();
                                        }
                                        break;
                                    case 3:
                                        if (node.ChildNodes[j] != null && node.ChildNodes[j].ChildNodes[0] != null)
                                        {
                                            desc3 = node.ChildNodes[j].ChildNodes[0].InnerText.Trim();
                                        }
                                        break;
                                    case 4:
                                        if (node.ChildNodes[j] != null && node.ChildNodes[j].ChildNodes[0] != null)
                                        {
                                            address = node.ChildNodes[j].ChildNodes[0].InnerText.Trim();
                                        }
                                        break;
                                    case 5:
                                        if (node.ChildNodes[j] != null && node.ChildNodes[j].ChildNodes[0] != null)
                                        {
                                            location = node.ChildNodes[j].ChildNodes[0].InnerText.Trim();
                                        }
                                        break;
                                    case 6:
                                        if (node.ChildNodes[j] != null && node.ChildNodes[j].ChildNodes[0] != null)
                                        {
                                            flagObsolete = node.ChildNodes[j].ChildNodes[0].InnerText.Trim();
                                        }
                                        break;
                                    
                                }
                                k++;
                            }

                            // data validation

                            if ((companyCode == String.Empty) || ( companyCode.Length > 50))
                            {
                                // this.Alert(string.Format(this.GetMessage("COM_ParameterLength"), this.GetLabel("SOM_QualificationCode"), "20"));
                                throw new Exception();
                            }

                            if ((desc1 == String.Empty) || (desc1.Length > 100) )
                            {
                                //this.Alert(string.Format(this.GetMessage("COM_ParameterLength"), this.GetLabel("SOM_QualificationDesc"), "60"));
                                throw new Exception();
                            }
                            if ((desc2 == String.Empty) || (desc2.Length > 100))
                            {
                                //this.Alert(string.Format(this.GetMessage("COM_ParameterLength"), this.GetLabel("SOM_QualificationDesc"), "60"));
                                throw new Exception();
                            }
                            if ((desc3 == String.Empty) || (desc3.Length > 100))
                            {
                                //this.Alert(string.Format(this.GetMessage("COM_ParameterLength"), this.GetLabel("SOM_QualificationDesc"), "60"));
                                throw new Exception();
                            }
                            //address can be null
                            if ((address != String.Empty) && ( address.Length > 200))
                            {
                                //this.Alert(string.Format(this.GetMessage("COM_ParameterLength"), this.GetLabel("SOM_QualificationDesc"), "60"));
                                throw new Exception();
                            }
                            //location ID can be null
                            //if ((location != String.Empty) && (location.Length > 10)) //Modify by zengshunbo Point 6 in 2009-02-10 SOMS_change_form_20090206.
                            if (location != String.Empty) //Add by zengshunbo Point 6 in 2009-02-10 SOMS_change_form_20090206.
                            {
                                //this.Alert(string.Format(this.GetMessage("COM_ParameterLength"), this.GetLabel("SOM_QualificationDesc"), "60"));
                                throw new Exception();
                            }
                            
                            //-----------------Modify by zengshunbo Point 6 in 2009-02-10 SOMS_change_form_20090206.-------------------
                            //else if ((location != String.Empty) && (location.Length <= 10) )
                            //{
                            //    // check if the location id existed
                            //    if (!MTRC.ODMS.DAL.SOM.CodeSetup.ExtParty.CheckLocaionIDExist(location))
                            //    {
                            //        throw new Exception();
                            //    }
                            //}
                            //-----------------End modify by zengshunbo Point 6 in 2009-02-10 SOMS_change_form_20090206.----------------

                            if ( flagObsolete != "Y" && flagObsolete != "N")
                            {
                                //Alert(this.GetLabel("SOM_FlagSOMAR") + GetMessage("SOM_ValueISYorN"));
                                throw new Exception();
                            }
                          
                        }
                        catch
                        {
                            i++;
                            hasERROR = true;

                            //add by SQB 2008/12/05 begin...
                            APJ.Util.Utility.AddAttribute(node, "StyleID", "ODMS", "ss", "urn:schemas-microsoft-com:office:spreadsheet");
                            //add by SQB 2008/12/05 end...

                            if (node.ChildNodes[0] != null)
                            {
                                APJ.Util.Utility.AddAttribute(node.ChildNodes[0], "StyleID", "ODMS", "ss", "urn:schemas-microsoft-com:office:spreadsheet");
                            }
                            if (node.ChildNodes[1] != null)
                            {
                                APJ.Util.Utility.AddAttribute(node.ChildNodes[1], "StyleID", "ODMS", "ss", "urn:schemas-microsoft-com:office:spreadsheet");
                            }
                            if (node.ChildNodes[2] != null)
                            {
                                APJ.Util.Utility.AddAttribute(node.ChildNodes[2], "StyleID", "ODMS", "ss", "urn:schemas-microsoft-com:office:spreadsheet");
                            }
                            if (node.ChildNodes[3] != null)
                            {
                                APJ.Util.Utility.AddAttribute(node.ChildNodes[3], "StyleID", "ODMS", "ss", "urn:schemas-microsoft-com:office:spreadsheet");
                            }
                            if (node.ChildNodes[4] != null)
                            {
                                APJ.Util.Utility.AddAttribute(node.ChildNodes[4], "StyleID", "ODMS", "ss", "urn:schemas-microsoft-com:office:spreadsheet");
                            }
                            if (node.ChildNodes[5] != null)
                            {
                                APJ.Util.Utility.AddAttribute(node.ChildNodes[5], "StyleID", "ODMS", "ss", "urn:schemas-microsoft-com:office:spreadsheet");
                            }
                            if (node.ChildNodes[6] != null)
                            {
                                APJ.Util.Utility.AddAttribute(node.ChildNodes[6], "StyleID", "ODMS", "ss", "urn:schemas-microsoft-com:office:spreadsheet");
                            }
                           

                            continue;
                        }

                        XmlNode xnode = APJ.Util.Utility.AddNode(xml.FirstChild, "row", "");
                        APJ.Util.Utility.AddAttribute(xnode, "idx", i.ToString());
                        APJ.Util.Utility.AddNode(xnode, "companyCode", "", companyCode);
                        APJ.Util.Utility.AddNode(xnode, "desc1", "", desc1);
                        APJ.Util.Utility.AddNode(xnode, "desc2", "", desc2);
                        APJ.Util.Utility.AddNode(xnode, "desc3", "", desc3);
                        APJ.Util.Utility.AddNode(xnode, "address", "", address);
                        APJ.Util.Utility.AddNode(xnode, "location", "", location);
                        APJ.Util.Utility.AddNode(xnode, "flagObsolete", "", flagObsolete);
                        

                    }
                    i++;
                }
                bool successful = true;
                DataTable dtReturn = new DataTable();
                //if (!hasERROR)
                //{
                    dtReturn = MTRC.ODMS.DAL.SOM.CodeSetup.ExtParty.CQAContractorCompanyUpload(this.ODMUser.ID, this.ODMUser.ID, ref successful, xml);
                //}

                if (successful)
                {


                    if ((dtReturn.Rows.Count > 0) || (hasERROR))
                    {
                        string stylePath = "ss:Workbook/ss:Styles";
                        string stylePathS22 = "ss:Workbook/ss:Styles/ss:Style[@ss:ID='ODMS_ExportExcel']";
                        XmlNode nodeS22 = xdoc.SelectSingleNode(stylePathS22, xnm);
                        if (nodeS22 == null)
                        {//not exist style ODMS, create dynamically for highlight
                            XmlNode nodeStyles = xdoc.SelectSingleNode(stylePath, xnm);
                            XmlNode nodeStyle = APJ.Util.Utility.AddNode(nodeStyles, "Style", "urn:schemas-microsoft-com:office:spreadsheet", "");
                            APJ.Util.Utility.AddAttribute(nodeStyle, "ID", "ODMS", "ss", "urn:schemas-microsoft-com:office:spreadsheet");
                            XmlNode nodeInterior = APJ.Util.Utility.AddNode(nodeStyle, "Interior", "urn:schemas-microsoft-com:office:spreadsheet", "");
                            APJ.Util.Utility.AddAttribute(nodeInterior, "Color", "#FF0000", "ss", "urn:schemas-microsoft-com:office:spreadsheet");
                            APJ.Util.Utility.AddAttribute(nodeInterior, "Pattern", "Solid", "ss", "urn:schemas-microsoft-com:office:spreadsheet");

                            XmlNode nodeStyle2 = APJ.Util.Utility.AddNode(nodeStyles, "Style", "urn:schemas-microsoft-com:office:spreadsheet", "");
                            APJ.Util.Utility.AddAttribute(nodeStyle2, "ID", "ODMS2", "ss", "urn:schemas-microsoft-com:office:spreadsheet");
                            XmlNode nodeInterior2 = APJ.Util.Utility.AddNode(nodeStyle2, "Interior", "urn:schemas-microsoft-com:office:spreadsheet", "");
                            APJ.Util.Utility.AddAttribute(nodeInterior2, "Color", "#FF0000", "ss", "urn:schemas-microsoft-com:office:spreadsheet");
                            APJ.Util.Utility.AddAttribute(nodeInterior2, "Pattern", "Solid", "ss", "urn:schemas-microsoft-com:office:spreadsheet");
                            nodeInterior2 = APJ.Util.Utility.AddNode(nodeStyle2, "NumberFormat", "urn:schemas-microsoft-com:office:spreadsheet", "");
                            APJ.Util.Utility.AddAttribute(nodeInterior2, "Format", "General Date", "ss", "urn:schemas-microsoft-com:office:spreadsheet");
                        }

                        foreach (DataRow row in dtReturn.Rows)
                        {

                            //---------------------huangyao----------
                            XmlNode node = nodelist.Item((int)row["idx"]);
                            for (int j = 0, k = 0; j < node.ChildNodes.Count; j++)
                            {
                                if (node.ChildNodes[j].Attributes["ss:Index"] != null)
                                {
                                    int h = 0;
                                    if (int.TryParse(node.ChildNodes[j].Attributes["ss:Index"].Value, out h))
                                    {
                                        k = h - 1;
                                    }
                                }

                                APJ.Util.Utility.AddAttribute(node.ChildNodes[j], "StyleID", "ODMS", "ss", "urn:schemas-microsoft-com:office:spreadsheet");

                                k++;
                            }
                            //--------------------------------------

                            ////---------------------commentted by huangyao----------
                            //APJ.Util.Utility.AddAttribute(nodelist.Item((int)row["idx"]).ChildNodes[0], "StyleID", "ODMS", "ss", "urn:schemas-microsoft-com:office:spreadsheet");
                            //APJ.Util.Utility.AddAttribute(nodelist.Item((int)row["idx"]).ChildNodes[1], "StyleID", "ODMS", "ss", "urn:schemas-microsoft-com:office:spreadsheet");
                            //APJ.Util.Utility.AddAttribute(nodelist.Item((int)row["idx"]).ChildNodes[2], "StyleID", "ODMS", "ss", "urn:schemas-microsoft-com:office:spreadsheet");
                            //APJ.Util.Utility.AddAttribute(nodelist.Item((int)row["idx"]).ChildNodes[3], "StyleID", "ODMS", "ss", "urn:schemas-microsoft-com:office:spreadsheet");
                            //APJ.Util.Utility.AddAttribute(nodelist.Item((int)row["idx"]).ChildNodes[4], "StyleID", "ODMS", "ss", "urn:schemas-microsoft-com:office:spreadsheet");
                            //APJ.Util.Utility.AddAttribute(nodelist.Item((int)row["idx"]).ChildNodes[5], "StyleID", "ODMS", "ss", "urn:schemas-microsoft-com:office:spreadsheet");
                            //APJ.Util.Utility.AddAttribute(nodelist.Item((int)row["idx"]).ChildNodes[6], "StyleID", "ODMS", "ss", "urn:schemas-microsoft-com:office:spreadsheet");
                            //---------------end------commentted by huangyao----------
                           
                        }
                        Response.Clear();
                        Response.Charset = "UTF-16";
                        Response.ContentEncoding = System.Text.Encoding.GetEncoding(1200);
                        Response.AddHeader("Content-disposition", "attachment;filename=" + fileName);
                        Response.ContentType = "application/vnd.ms-excel";
                        xdoc.Save(Response.OutputStream);
                        xdoc = null;
                        Response.End();

                    }
                    else
                    {
                        Alert(GetMessage("SOM_UpdateSuccessful"));
                    }
                }
                else
                {
                    xdoc = null;
                    Alert(GetMessage("SOM_UpdateError"));
                }
                xml = null;
            }
            catch //(Exception ex)
            {
                Alert(GetMessage("SOM_UpdateError"));
            }
            finally
            {
                xdoc = null;
            }
        }

        protected void btnDownMTR_Click(object sender, EventArgs e)
        {
            DataSet ds = MTRC.ODMS.DAL.SOM.CodeSetup.ExtParty.GetAllExpartyList();
            DataTable dtSearchResult = ds.Tables[0];
            //dtSearchResult.TableName = this.GetLabel("SOM_CQAContractorCompanyUpload");
            dtSearchResult.TableName = "CQA Contractor Company Upload";
            dtSearchResult.Columns.Remove("ExtPartyID");
            dtSearchResult.Columns.Remove("FlagCQA");
            dtSearchResult.Columns.Remove("LastUpdUser");
            dtSearchResult.Columns.Remove("LastUpdTime");
            dtSearchResult.Columns.Remove("ActingasUser");
            dtSearchResult.Columns.Remove("Module1");
            dtSearchResult.Columns.Remove("Module2");
            dtSearchResult.Columns.Remove("Module3");
            dtSearchResult.Columns.Remove("Module4");
            dtSearchResult.Columns.Remove("Module5");
            dtSearchResult.Columns.Remove("Module6");
            dtSearchResult.Columns.Remove("Module7");
            dtSearchResult.Columns.Remove("Module8");

            //------------ modify by zengshunbo 2008-12-11 actionlog(0709) ----------

            dtSearchResult.Columns[0].ColumnName = this.GetLabel("SOM_CompanyCode");
            dtSearchResult.Columns[1].ColumnName = this.GetLabel("COM_Description1");
            dtSearchResult.Columns[2].ColumnName = this.GetLabel("COM_Description2");
            dtSearchResult.Columns[3].ColumnName = this.GetLabel("COM_Description3");
            dtSearchResult.Columns[4].ColumnName = this.GetLabel("SOM_Address");
            dtSearchResult.Columns[5].ColumnName = this.GetLabel("COM_Location");
            dtSearchResult.Columns[6].ColumnName = this.GetLabel("SOM_VoidYesOrNo");

            //dtSearchResult.Columns[0].ColumnName = "Company Code";
            //dtSearchResult.Columns[1].ColumnName = "Description1";
            //dtSearchResult.Columns[2].ColumnName = "Description2";
            //dtSearchResult.Columns[3].ColumnName = "Description3";
            //dtSearchResult.Columns[4].ColumnName = "Address";
            //dtSearchResult.Columns[5].ColumnName = "Location";
            //dtSearchResult.Columns[6].ColumnName = "Valid?(Y/N)";


            //--------- End modify by zengshunbo 2008-12-11 -------------------------


            Common.ExportExcel_showHHMM(ds, Context, "CQAContractorCompanyUpload.xls","som_upload");
            dtSearchResult = null;
            ds = null;
        }

        protected void btnDownTemplte_Click(object sender, EventArgs e)
        {
            DataSet ds = new DataSet();

            //-------------- Modify by zengshunbo 2008-12-11 action log(0709) -----------------

            DataTable dt = new DataTable(this.GetLabel("SOM_CQAContractorCompanyUpload"));
            dt.Columns.Add(this.GetLabel("SOM_CompanyCode"));//
            dt.Columns.Add(this.GetLabel("COM_Description1"));//
            dt.Columns.Add(this.GetLabel("COM_Description2"));//
            dt.Columns.Add(this.GetLabel("COM_Description3"));//
            dt.Columns.Add(this.GetLabel("SOM_Address"));//new
            dt.Columns.Add(this.GetLabel("COM_Location"));//
            dt.Columns.Add(this.GetLabel("SOM_VoidYesOrNo"));//   

            //DataTable dt = new DataTable("CQA Contractor Company Upload");
            //dt.Columns.Add("Company Code");//
            //dt.Columns.Add("Description1");//
            //dt.Columns.Add("Description2");//
            //dt.Columns.Add("Description3");//
            //dt.Columns.Add("Address");//
            //dt.Columns.Add("Location");//
            //dt.Columns.Add("Valid?(Y/N)");// 

            //------------- Modify by zengshunbo 2008-12-11 action log(0709)  ----------------

            ds.Tables.Add(dt);
            Common.ExportExcel(ds, Context, "CQAContractorCompanyUpload.xls");
        }
    }
}
